package com;

import io.prediction.Event;
import io.prediction.EventClient;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.JavaType;
import com.log.PioEventTimeVo;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.util.JsonMapper;

@Service
@ConfigurationProperties
public class PredictionIoService {
	
	private static Logger logger = LoggerFactory.getLogger(PredictionIoService.class);
	
		private String predictionioUrl;
		public String getPredictionioUrl() {
			return predictionioUrl;
		}
		public void setPredictionioUrl(String predictionioUrl) {
			this.predictionioUrl = predictionioUrl;
		}
		public String getAccessKey() {
			return accessKey;
		}
		public void setAccessKey(String accessKey) {
			this.accessKey = accessKey;
		}
		private String accessKey;
		

		
		public String creatEvent(Event event){
			 EventClient client = new EventClient(accessKey, predictionioUrl);

			String eventId = "";
			try {
				eventId = client.createEvent(event);
			} catch (ExecutionException | InterruptedException | IOException e) {
				e.printStackTrace();
//				logger.info("type : "+event.getEntityType() +" , id : "+event.getEntityId() +", send to PIO fail");
			}finally{
				client.close();
			}			
			return eventId;
		}
		JsonMapper jsonMapper = JsonMapper.nonDefaultMapper();
		DateTimeFormatter format = ISODateTimeFormat.dateTimeParser();
		public PioEventTimeVo getEventTime(String entityId){
			String queryStr = predictionioUrl+"/events.json?accessKey="+accessKey+"&entityType=piwik_log_link_visit_action&entityId="+entityId;
			try {
				String res = 	Unirest.get(queryStr).asString().getBody();
				
				if (!res.startsWith("[")) {
					logger.info("error message :"+res);
					return null;
				}
				 
				 JavaType beanListType = jsonMapper.contructCollectionType(List.class, Map.class);
      		   	List<Map<String, Object>> mapList = jsonMapper.fromJson(res, beanListType);
      		   	Map<String, Object>  eventMap = mapList.get(0);
      		   	String eventTimeStr = eventMap.get("eventTime").
      		   			toString();
      			String creationTimeStr= eventMap.get("creationTime").
      					toString();
      			PioEventTimeVo pioEventTimeVo = new PioEventTimeVo();
      			pioEventTimeVo.eventTime = new DateTime(eventTimeStr);
      			pioEventTimeVo.creationTime = new DateTime(creationTimeStr);
				return pioEventTimeVo;
			} catch (UnirestException e) {
				e.printStackTrace();
			}
			return  null;
		}
		

}
